<?php
/**
 * Created by PhpStorm.
 * User: Administrator
 * Date: 2017/5/4
 * Time: 17:24
 */

namespace Home\Controller;

use DH16\Libs\Controller;
use DH16\Tools\Code;
use DH16\Tools\Model;

/**
 * Class UserController
 * @package Home\Controller
 * 用户管理控制器
 */
class UserController extends Controller
{
    private $model;  //数据库对象

    /**
     * 构造函数
     */
    public function __construct()
    {
        $this->model = new Model();
    }

    /**
     * 登录
     */
    public function login(){
        //2.判断
        if(IS_POST){
            //3.获得所有数据
            $username = $_POST['username'];
            $password = md5($_POST['password']);
            $code = $_POST['code'];

            //4.获得数据库中的数据
            $data = $this->model->query("select * from user where username='{$username}'");
            $data = $data[0];
            //5.判断用户名是否存在
            if($data['username']!==$username){
                $this->error("用户名不存在");
            }
            //6.判断密码是否正确
            if($password!==$data['password']){
                $this->error('密码错误');
            }
            //7.判断验证码是否正确
            if(strtolower($code)!==strtolower($_SESSION['code'])){
                $this->error('验证码错误');
            }
            //8.存储用户名
            $_SESSION['username']=$username;
            $this->success('登录成功','index.php?c=index&a=index');
        }
        //1.载入模板
        $this->display();
    }

    /**
     * 验证码
     */
    public function code(){
        $code = new Code();
        $code->make();
    }

    /**
     * 注销
     */
    public function out(){
        session_unset();
        session_destroy();
        $this->success('注销成功','index.php?c=index&a=index');
    }

    /**
     * 注册
     */
    public function register(){
        if($_POST){
            //获得输入的数据
            $username = $_POST['username'];
            $password = md5($_POST['password']);
            $confirm = md5($_POST['confirm']);

//            判断用户名是否存在
            $Data = $this->model->query("select * from user");
            foreach($Data as $v){
                if($v['username']==$username){
                    $this->error('用户名已存在');
                }
            }

            //判断两次密码是否一致
            if($password!==$confirm){
                $this->error('两次密码输入不一致');
            }

            $rows = $this->model->exec("insert into user set username='{$username}',password='{$password}'");
            if($rows){
                $this->success('注册成功','index.php?c=user&a=login');
            }else{
                $this->error("注册失败");
            }

        }
        //1.载入模板
        $this->display();
    }
}